var express = require('express');
require('express-async-errors');
var router = express.Router();
var tools = require('../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.redirect('article/index');
});

router.get('/index', async function (req, res, next) {
  var page = req.query.page || 1;
  page = parseInt(page);

  var pagesize = 2;
  var offset = (page - 1) * pagesize;

  //总页数
  function get_total_page(pagesize) {
    return new Promise((resolve, reject) => {
      pool.query(`SELECT count(*) as t from article`, function (error, results, fields) {
        if (error) reject(0);
        resolve(Math.ceil(results[0]['t'] / pagesize));
      });
    });
  }

  var total_page = await get_total_page(pagesize);
  console.log(total_page);

  pool.query(`SELECT * from article order by itemid desc limit ${offset},${pagesize}`, function (error, results, fields) {
    if (error) throw error;
    res.render('admin/article/index', { data: results, url: config.url, total_page: total_page, page: page });
  });


});

router.get('/add', function (req, res, next) {
  res.render(req.TPL, {});
});

router.post('/add', function (req, res, next) {
  console.log('/add');
  var post = req.body;
  var title = post.title.trim();
  if (!title) {
    res.render('msg', { code: 0, msg: '标题不能为空', url: '' });
  }
  var content = post.content.trim();
  if (!content) {
    res.render('msg', { code: 0, msg: '内容不能为空', url: '' });
  }

  pool.query('INSERT INTO article SET ?', { title: title, content: content }, function (error, results, fields) {
    if (error) throw error;
    var insertId = results.insertId;
    if (insertId) {
      res.render('msg', { code: 1, msg: '操作成功', url: '/admin/article/index' });
    } else {
      res.render('msg', { code: 0, msg: '操作失败', url: '' });
    }

  });

});

router.get('/mod/:itemid', function (req, res, next) {
  console.log('/mod', req.params);
  var itemid = parseInt(req.params.itemid);
  if (!itemid) {
    res.render('msg', { code: 0, msg: '数据不存在', url: '' });
  }

  pool.query('SELECT * from article where itemid=?', [itemid], function (error, results, fields) {
    if (error) throw error;
    if (results.length == 0) {
      res.render('msg', { code: 0, msg: '操作失败', url: '' });
    }
    res.render('admin/article/mod', { data: results[0] });
  });
});


router.post('/mod/:itemid', function (req, res, next) {
  console.log('/mod');
  var post = req.body;
  var itemid = parseInt(req.params.itemid);

  if (!itemid) {
    res.render('msg', { code: 0, msg: '数据不存在', url: '' });
  }

  var title = post.title.trim();
  if (!title) {
    res.render('msg', { code: 0, msg: '标题不能为空', url: '' });
  }
  var content = post.content.trim();
  if (!content) {
    res.render('msg', { code: 0, msg: '内容不能为空', url: '' });
  }

  pool.query('update article SET title=?,content=? where itemid=?', [title, content, itemid], function (error, results, fields) {
    if (error) throw error;
    var r = results.affectedRows;
    if (r) {
      res.render('msg', { code: 1, msg: '操作成功', url: '/admin/article/index' });
    } else {
      res.render('msg', { code: 0, msg: '操作失败', url: '' });
    }

  });

});

router.get('/del/:itemid', function (req, res, next) {
  console.log('/del', req.params);
  var itemid = parseInt(req.params.itemid);
  if (!itemid) {
    res.render('msg', { code: 0, msg: '数据不存在', url: '' });
  }

  pool.query('delete from article where itemid=?', [itemid], function (error, results, fields) {
    if (error) throw error;
    if (results.affectedRows.length == 0) {
      res.render('msg', { code: 0, msg: '操作失败', url: '' });
    } else {
      res.render('msg', { code: 1, msg: '操作成功', url: '' });
    }
  });
});

//使用全新model
router.get('/test', async function (req, res, next) {
  const article_model = require(tools.modelPath + 'article');
  console.log(article_model.demo());
  let data = await model.select("select itemid,title from article order by itemid desc");
  res.json({
    code: 0,
    msg: '',
    data: data,
  });
});

//


module.exports = router;